#ifndef IntegralImage_H_
#define IntegralImage_H_

template <class type> class IntegralImage
{
	public:
		type ** integral;
		int w;
		int h;
		void setup(type ** matrix,int width, int height)
		{
			w = width;
			h = height;
			integral = new type * [width];
			for(int i = 0; i < width; i++){
				integral[i] = new type[height];
			}
			
			integral[0][0] = matrix[0][0];
			for(int i = 1; i < width; i++){
				integral[i][0] = matrix[i][0]+integral[i-1][0];
			}
			
			for(int j = 1; j < height; j++){
				integral[0][j] = matrix[0][j]+integral[0][j-1];
			}
			for(int i = 1; i < width; i++){
				for(int j = 1; j < height; j++){
					integral[i][j] = matrix[i][j]+integral[i][j-1]+integral[i-1][j]-integral[i-1][j-1];
				}
			}
		}
		
		type sum(int tx,int ty, int bx, int by)
		{
			return integral[tx][ty] + integral[bx][by] - integral[tx][by] - integral[bx][ty];
		}
		
		void clear()
		{
			for(int i = 0; i < w; i++){delete[] integral[i];}
			delete[] integral;
		}
};
#endif
